import httpx
import hashlib
import base64
import time
import random
from typing import Optional
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class RongLianSMS:
    """容联云短信服务"""
    
    def __init__(self):
        # 容联云账号信息
        self.account_sid = "2c94811c985fa32501986020fcef0052"
        self.auth_token = "d374a7ada9a546a9a79844b3c9624589"
        self.app_id = "2c94811c985fa32501986020feb80059"
        
        # API配置
        self.base_url = "https://app.cloopen.com:8883"
        self.send_sms_url = f"{self.base_url}/2013-12-26/Accounts/{self.account_sid}/SMS/TemplateSMS"
        
    def _generate_signature(self, timestamp: str) -> str:
        """生成认证签名"""
        # 拼接字符串：AccountSid + AuthToken + timestamp
        string_to_sign = f"{self.account_sid}{self.auth_token}{timestamp}"
        
        # 使用MD5加密
        signature = hashlib.md5(string_to_sign.encode('utf-8')).hexdigest()
        
        # 转换为大写
        return signature.upper()
    
    def _generate_auth_header(self) -> tuple:
        """生成认证请求头"""
        timestamp = str(int(time.time()))
        signature = self._generate_signature(timestamp)
        
        # 拼接认证字符串：AccountSid:timestamp
        auth_string = f"{self.account_sid}:{timestamp}"
        
        # Base64编码
        auth_header = base64.b64encode(auth_string.encode('utf-8')).decode('utf-8')
        
        return auth_header, timestamp
    
    def generate_verification_code(self) -> str:
        """生成6位数字验证码"""
        return str(random.randint(100000, 999999))
    
    async def send_verification_code(self, phone: str, code: str) -> dict:
        """
        发送验证码短信
        
        Args:
            phone: 手机号
            code: 验证码
            
        Returns:
            dict: 发送结果
        """
        try:
            # 生成认证信息
            auth_header, timestamp = self._generate_auth_header()
            
            # 请求头
            headers = {
                "Accept": "application/json",
                "Content-Type": "application/json;charset=utf-8",
                "Authorization": auth_header
            }
            
            # 请求体
            data = {
                "to": phone,
                "appId": self.app_id,
                "templateId": "1",  # 使用默认模板ID，实际项目中需要申请
                "datas": [code, "5"]  # 验证码和有效期（分钟）
            }
            
            # 发送请求
            async with httpx.AsyncClient(timeout=30.0) as client:
                response = await client.post(
                    self.send_sms_url,
                    headers=headers,
                    json=data
                )
                
                result = response.json()
                
                # 记录日志（手机号脱敏）
                masked_phone = self._mask_phone(phone)
                logger.info(f"发送验证码到 {masked_phone}: {result}")
                
                # 解析响应
                if result.get("statusCode") == "000000":
                    return {
                        "success": True,
                        "message": "验证码发送成功",
                        "data": result
                    }
                else:
                    return {
                        "success": False,
                        "message": f"验证码发送失败: {result.get('statusMsg', '未知错误')}",
                        "data": result
                    }
                    
        except Exception as e:
            logger.error(f"发送验证码异常: {str(e)}")
            return {
                "success": False,
                "message": f"发送验证码异常: {str(e)}",
                "data": None
            }
    
    def _mask_phone(self, phone: str) -> str:
        """手机号脱敏处理"""
        if len(phone) == 11:
            return f"{phone[:3]}****{phone[-4:]}"
        return phone

# 创建全局实例
sms_service = RongLianSMS()
